import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_rider/api/api.dart';
import 'package:flutter_rider/event/click_close_stations_event.dart';
import 'package:flutter_rider/generated/r.dart';
import 'package:flutter_rider/main/widgets/dialog/alert_dialog.dart';
import 'package:flutter_rider/main/widgets/ext/u_text.dart';
import 'package:flutter_rider/main/widgets/pop/pop_car_status.dart';
import 'package:flutter_rider/main/widgets/state/state_layout.dart';
import 'package:flutter_rider/main/widgets/ui_constant.dart';
import 'package:flutter_rider/main/models/car_model.dart';
import 'package:flutter_rider/main/models/station_model.dart';
import 'package:flutter_rider/utils/open_utils.dart';
import 'package:flutter_rider/utils/screen_fit.dart';
import 'package:flutter_rider/event/change_stations_event.dart';
import 'package:flutter_rider/main.dart';
import 'package:flutter_rider/utils/tip.dart';
import 'package:flutter_svg/svg.dart';

class PopCarList extends StatefulWidget {

  StationModel? station;
  ///是否只显示空闲中和调配中的车
  bool isShowIdleCar;

  PopCarList(this.station,[this.isShowIdleCar = false]);
  
  @override
  State createState() => _PopCarListState();
}

class _PopCarListState extends State<PopCarList> {
  final _inputController = TextEditingController(text: "");
  final StateLayoutController _stateLayoutController = StateLayoutController();
  List<CarModel> _data = [];
  final List<CarModel> _result = [];
  late StreamSubscription _eventFn;

  @override
  void initState() {
    super.initState();
    _eventFn = eventBus.on<ChangeStationsEvent>().listen((event) {
      Navigator.of(context).pop();
      _result.clear();
      _stateLayoutController.reload();

    });
  }

  @override
  void dispose() {
    super.dispose();
    _eventFn.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.only(left: MediaQuery.of(context).padding.left, right: MediaQuery.of(context).padding.right),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.vertical(top: Radius.circular(8.rpx)),
      ),
      child: Column(
        children: [
          8.hspace,
          Container(
            width: 36.rpx,
            height: 5.rpx,
            decoration: BoxDecoration(
              color: Colors.black.withOpacity(0.26),
              borderRadius: BorderRadius.circular(2.rpx),
            ),
          ),
          Container(
              height: 70.rpx,
              alignment: Alignment.center,
              child: Row(
                  // mainAxisAlignment: MainAxisAlignment.center,
                  // crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    16.wspace,
                    InkWell(child: 
                    SvgPicture.asset(R.image_left,
                        width: 24.rpx, height: 24.rpx),
                      onTap: _backClick,
                    ),
                    4.wspace,
                    Expanded(
                        child: Container(
                      alignment: Alignment.center,
                      child: UText.get("车辆列表", Colors.black, 20.rpx,
                          fw: FontWeight.bold),
                    )),
                    4.wspace,
                    InkWell(child: 
                    SvgPicture.asset(R.image_close,
                        width: 24.rpx, height: 24.rpx),
                      onTap: _closeClick,
                    ),
                    16.wspace,
                  ])),
          
          _renderInput(), 
          // 16.hspace,
          Visibility(
            visible: widget.station?.station_name.isNotEmpty ?? false ,
            child:  Container(
              alignment:Alignment.center,
              height: 54.rpx,
              child: 
              RichText(text: 
              TextSpan(
              text: "车辆调配至 ",
              style: TextStyle(color: Colors.black,fontSize: 14.rpx,fontWeight: FontWeight.bold),
              children: [
                TextSpan(
              text: widget.station?.station_name,
              style: TextStyle(color: UIColor.color_primary,fontSize: 14.rpx,fontWeight: FontWeight.bold),
              
              )
              ]
              ),
              
              )
              // UText.get("车辆调配", Colors.black, 20.rpx,
                          // fw: FontWeight.bold)
            ,
            )
          ),
          Container(
            margin: EdgeInsets.only(left: 10.rpx, right: 10.rpx),
            height: 0.5.rpx,
            color: const Color(0xffE7E7E7),
          ),
          Expanded(
            child: StateLayout(
              controller: _stateLayoutController,
              dataCallback: _onDataCallback,
              url: "/car/list?page_size=200",
              childBuilder: _renderContent,
            ),
          ),
        ],
      ),
    );
  }

  _backClick() {
    print("返回");
    Navigator.pop(context);
    // if (widget.type == PopEnterType.map){
    //     eventBus.fire(ClickMapPopCarEvent());
    // }
    // else{
    //     eventBus.fire(ClickMangerPopCarEvent());
    // }
    
    
  }

   _closeClick() {
    print("关闭");
   
   if (widget.station != null){
        eventBus.fire(ClickCloseStationsEvent());
    }
    Navigator.pop(context);
  }

  _onDataCallback(dynamic data) {
    
    
    List list = data["list"];
    
    list.forEach((element) => _data.add(CarModel.fromMap(element)));

    if (widget.isShowIdleCar) {
    ///任务状态  -1=不可用 2 || 5 =空闲中， 3=任务中	4 调配中
    _data = _data.where((element) => element.status == 2 || element.status == 5 || element.status == 4).toList();
    }
    _result.addAll(_data);

    setState(() {
      
    });

  }

  

  _renderTab() {
    var tabHeight = 40.rpx;
    return Row(
      children: [
        24.wspace,
        Expanded(
          child: Container(
            width: 100,
            height: tabHeight,
            alignment: Alignment.centerLeft,
            child: UText.get("车辆编号", Colors.black.withOpacity(0.4), 16.rpx),
          ),
        ),
        Container(
          width: 100,
          height: tabHeight,
          alignment: Alignment.centerLeft,
          child: UText.get("状态", Colors.black.withOpacity(0.4), 16.rpx),
        ),
        // Container(
        //   width: 80,
        //   height: tabHeight,
        //   alignment: Alignment.centerLeft,
        //   child: UText.get("操作", Colors.black.withOpacity(0.4), 16.rpx),
        // ),
        24.wspace
      ],
    );
  }

  Widget _renderInput() {
    return Container(
      color: UIColor.color_content,
      padding: EdgeInsets.symmetric(
        horizontal: 16.rpx,
      ),
      child: TextField(
        onChanged: _onTextChange,
        controller: _inputController,
        textInputAction: TextInputAction.search,
        maxLength: 20,
        decoration: InputDecoration(
          constraints: BoxConstraints(minHeight: 44.rpx, maxHeight: 44.rpx),
          counterText: "",
          contentPadding: EdgeInsets.symmetric(vertical: 6.rpx, horizontal: 12.rpx),
          isCollapsed: true,
          border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(
                2.rpx,
              ),
              borderSide: BorderSide.none),
          prefixIcon: Padding(
            padding: EdgeInsets.only(left: 12.rpx, right: 4.rpx),
            child: Icon(
              Icons.search,
              size: 18.rpx,
              color: Colors.black.withOpacity(0.4),
            ),
          ),
          prefixIconConstraints: BoxConstraints(maxHeight: 16.rpx),
          hintText: "搜索车辆编号",
          hintStyle: TextStyle(color: Colors.black.withOpacity(0.4)),
          filled: true,
          fillColor: UIColor.color_input,
          suffixIconConstraints: BoxConstraints(maxHeight: 16.rpx),
          suffixIcon: _inputController.text.isNotEmpty
              ? Container(
                  padding: EdgeInsets.only(right: 6.rpx),
                  child: GestureDetector(
                    child: Icon(
                      Icons.close,
                      color: UIColor.color_t3,
                      size: 20.rpx,
                    ),
                    onTap: () {
                      _inputController.text = "";
                      _onTextChange("");
                    },
                  ),
                )
              : null,
        ),
      ),
    );
  }

  _onTextChange(String text) {
    if (text.isEmpty) {
      setState(() {
        _result.clear();
        _result.addAll(_data);
      });
    } else {
      _result.clear();

      _data.forEach((element) {
        //把用户输入的转为大写去匹配
        var upperCaseText = text.toUpperCase();
        if (element.car_no.contains(upperCaseText)) {
          _result.add(element);
        }
      });


      // for (int i = 0; i < _data["list"].length; i++) {
      //   var id = _data["list"][i]["car_no"] as String;
      //   id = id.toLowerCase();
      //   if (id.contains(text)) {
      //     _result.add(_data["list"][i]);
      //   }
      // }
      setState(() {});
    }
  }

  Widget _renderContent(dynamic data) {
    if (_data.length == 0) {
      return Center(
        child: UText.getSubText("暂无数据内容"),
      );
    }
    return ListView.separated(
      itemBuilder: _renderItem,
      itemCount: _result.length,
      separatorBuilder: _renderSeparator,
    );
  }

  Widget _renderContent2(dynamic data) {
    Widget child;
    if (_result.isEmpty && _inputController.text.isNotEmpty) {
      child = Center(
        child: UText.getSubText("找不到该车辆，请重新输入"),
      );
    } else {
      child = ListView.separated(
        itemBuilder: _renderItem,
        itemCount: _result.length,
        separatorBuilder: _renderSeparator,
      );
    }
    return Column(
      children: [
        _renderInput(),
        _renderTab(),
        Container(
          margin: EdgeInsets.only(left: 10.rpx, right: 10.rpx),
          height: 0.5.rpx,
          color: const Color(0xffE7E7E7),
        ),
        Expanded(child: child),
      ],
    );
  }

  Widget _renderSeparator(BuildContext context, int index) {
    return Container(
      margin: EdgeInsets.only(left: 10.rpx, right: 10.rpx),
      height: 0.5.rpx,
      color: const Color(0xffE7E7E7),
    );
  }

  Widget _renderItem(BuildContext context, int index) {
    var item = _result[index];
    Widget stText;
    if (item.status == 3) {
      stText = UText.get("任务中", UIColor.color_work, 16.rpx);
    } else if (item.status == 2  || item.status == 5) {
      stText = UText.get("空闲中", UIColor.color_wait, 16.rpx);
    } else if (item.status == 4) {
      stText = UText.get("调配中", UIColor.color_dispatch, 16.rpx);
    } else if (item.status == -1) {
      stText = UText.get("不可用", UIColor.color_none, 16.rpx);
    }else {
      stText = UText.get("未知", UIColor.color_none, 16.rpx);
    }
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      child: SizedBox(
        width: double.infinity,
        height: 64.rpx,
        child: Row(
          children: [
            24.wspace,
            Expanded(child: UText.get(item.car_no, Colors.black, 16.rpx, fw: FontWeight.w600)),
            SizedBox(
                width: 100.rpx,
                child: stText),
            Icon(Icons.navigate_next, size: 24.rpx, color: UIColor.color_t3),
            24.wspace
          ],
        ),
      ),
      onTap: () {

        if (widget.station != null){
            
            CustomAlertDialog.show(context,
            title: "确定调度车辆吗？", content: "确定调度车辆${item.car_no}去站点${widget.station?.station_name}吗？", onConfirm: () {
            send_dispatch(item.id,item.car_no,item.status);
        });
        }else{
        Navigator.of(context).pop();
        double percent = item.status == 3?0.85:0.35;
        OpenUtils.pop2(context, PopCarStatus(item.id,PopEnterType.map, title: item.car_no));
        
        }

        
      },
    );
  }


  send_dispatch(int car_id,String car_no,int status) {
    var url = "/driver/send_dispatch";
    if (status == 4) { //调配中的车辆 调用变更终点的接口
      url = "/driver/change_destination";
    } 

    var json = {};
    json["car_id"] = (car_id).toString();
    json["station_id"] = (widget.station?.station_id).toString();


    Api.submitx(context, url, data: json, progress: false, success: (data) {
      // if (widget.lx == 1) {
        Tip.show(car_no + '调配成功');
      // } else {
      //   Tip.show(widget.car_no + '变更成功');
      // }
      eventBus.fire(ClickCloseStationsEvent());
      Navigator.of(context).pop();
    }, failTip: "提交失败", fail: (_) {});
  }



}